package com.affaris.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.affaris.common.QueryPageParam;
import com.affaris.common.Result;
import com.affaris.entity.News;

import com.affaris.service.NewsService;
import com.affaris.service.SysFileService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lucas
 * @since 2023-05-15
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private SysFileService sysFileService;

    //新增
    @PostMapping("/save")
    public Result save(@RequestBody News news) {
        return newsService.save(news) ? Result.suc() : Result.fail();
    }

    //删除
    @GetMapping("/delete")
    public Result delete(@RequestParam String id) {

        return newsService.removeById(id) ? Result.suc() : Result.fail();
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody News news) {

        return newsService.updateById(news) ? Result.suc() : Result.fail();
    }

    //查询
    @PostMapping("/page")
    public Result page(@RequestBody QueryPageParam queryPageParam) {
        HashMap param = queryPageParam.getParam();
        String title = (String) param.get("title");
        String organization = (String) param.get("organization");

        Page<News> page = new Page();
        page.setCurrent(queryPageParam.getPageNum());
        page.setSize(queryPageParam.getPageSize());

        LambdaQueryWrapper<News> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(title) && !"null".equals(title)) {
            lambdaQueryWrapper.like(News::getTitle, title);
        }
        if (StringUtils.isNotBlank(organization) && !"null".equals(organization)) {
            lambdaQueryWrapper.eq(News::getOrganization, organization);
        }

        IPage result = newsService.page(page, lambdaQueryWrapper);
        return Result.suc(result.getRecords(), result.getTotal());
    }

    //上传文件
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        //
        File uploadParentFile = new File(fileUploadPath);
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }
        String uuid = IdUtil.fastSimpleUUID();  //文件唯一标识码
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUUID);
        //存储到磁盘中
        file.transferTo(uploadFile);
        String url = "http://localhost:8090/news/" + fileUUID;
        return url;
    }


    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String FileUUID, HttpServletResponse response) throws IOException {
        //获取标识码文件
        File uploadFile = new File(fileUploadPath + FileUUID);
        //输出流格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Type", "application;filename=" + URLEncoder.encode(FileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");
        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();

    }

}

